<%@ page language="java" contentType="text/html; charset=UTF-8"	 pageEncoding="UTF-8"%>
<%@ include file="../include/laypublic.jsp"%>
<!DOCTYPE html>
<html>
<head>
</head>
  <title>底线标准表单</title>
  <style type="text/css">
  	.layui-form-select dl{
		max-height: 150px; // 原值为300，调节高度建议为50的倍数
	}
	.layui-form-label{width: 60px;}
	#add_line_form div i .layui-icon{
		width: 60px;
		height: 60px;
		padding: 2px 5px;
		background-color: green;
	}
  </style>
</head>

<body>
  <div class="layui-fluid">
    <div class="layui-card">
      <!-- 查询区域  -->
      <div id="query-form" class="layui-form layui-card-header layuiadmin-card-header-auto">
       	<div class="layui-form-item">
          	<div class="layui-inline">
            	<label class="layui-form-label">地区</label>
            	<div class="layui-input-inline">
              		<select name ="queryProvinceId" lay-filter="query_provinceId" lay-search>
                    	<option value="0">全国通用</option>
	                    <c:if test="${not empty provinces }">
	            			<c:forEach items="${provinces}" var="province">
	            				<option value="${province.id}">${province.sname }</option>
	           				</c:forEach>
	            		</c:if>
	                 </select>
	             </div>
	             <div class="layui-input-inline">
	                 <select name ="queryCityId" id="query_city" lay-filter="query_cityId" lay-search>
                    	<option value="">请选择市</option>
	                 </select>
	             </div>
	             <div class="layui-input-inline">
	                 <select name ="queryAreaId" id="query_area" lay-filter="query_areaId" lay-search>
                    	<option value="">请选择区/县</option>
	                 </select>
            	</div>
          	</div>
			<div class="layui-inline">
				<button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-preProject-search">
					<i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>查询
				</button>
				<button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-user-back-reset">
					<i class="layui-icon layui-icon-fonts-clear  layuiadmin-button-btn"></i>重置
				</button>
			</div>
        </div>
      </div>
  	  <!-- 按钮区域  -->
      <div class="layui-card-body">
      	<div style="padding-bottom: 10px;">
			<button class="layui-btn layuiadmin-btn-admin " data-type="add">
				<i class="layui-icon layui-icon-add-1 layuiadmin-button-btn"></i>新建
			</button>
			<button class="layui-btn layuiadmin-btn-admin layui-hide" data-type="export" onclick="exportList();">
				<i class="layui-icon layui-icon-export layuiadmin-button-btn"></i>导出
			</button>
        </div>

		  <div class="layui-tab-item layui-show">
			  <table id="LAY-strandard-create-manage" lay-filter="LAY-strandard-create-manage"></table>
			  <div id="table-foot"></div>
		  </div>
      </div>
    </div>
  </div>

  <form class="layui-form" lay-filter="add_line_form" id="add_line_form" style="padding: 20px 30px 0 0;display:none">
  	  <input type="hidden" name="id" value="${baseLine.id}"/>
	  	 <div class="layui-form-item">
             <label class="layui-form-label" >地区</label>
             <input type="hidden" name = "sgCityName">
             <div class="layui-input-inline" style="width: 114px">
                 <select name ="refProvinceId"  id="" lay-filter="select_provinceId" lay-verify="required" lay-search>
					 <option value="0">全国通用</option>
                     <c:if test="${not empty provinces }">
            			<c:forEach items="${provinces}" var="province">
            				<option value="${province.id}">${province.sname }</option>
           				</c:forEach>
            		</c:if>
                 </select>
             </div>
             <div class="layui-input-inline" style="width: 114px">
                 <select name="refCityId" id="select_city" lay-filter="select_city" lay-search>
                 </select>
             </div>
             <div class="layui-input-inline" style="width: 114px">
                 <select name="refAreaId" id="select_area" lay-filter="select_area"  lay-search>
                 </select>
             </div>
         </div>
		<div class="layui-form-item" id="linkRow1">
		  	 <div class="layui-inline">
			 	  <label class="layui-form-label">标准1</label>
				  <div class="layui-input-inline" style="width: 150px;" id="standardSelect">
					  <input type="hidden" name="standardId" value="${standardSub.id}"/>
					  <select name="standardName" lay-filter="standardName" lay-verify="required" lay-search>
	                        <c:if test="${not empty standardNames }">
		              			<c:forEach items="${standardNames}" var="enumOjb">
		              				<option value="${enumOjb.typeId}">${enumOjb.typeName }</option>
			            		</c:forEach>
		              		</c:if>
					  </select>
				  </div>
				  <div class="layui-input-inline" style="width: 70px" id="strandardRuleSelect">
					  <select name="standardRule" lay-verify="required">
						  <option value="&gt;" <c:if test="${baseLine.standard=='&gt;'}"> selected="selected"> </c:if> > &gt; </option>
						  <option value="&lt;" <c:if test="${baseLine.standard=='&lt;'}"> selected="selected"> </c:if> > &lt; </option>
						  <option value="=" <c:if test="${baseLine.standard=='='}"> selected="selected"> </c:if> > = </option>
						  <option value="≥" <c:if test="${baseLine.standard=='≥'}"> selected="selected"> </c:if>> ≥ </option>
						  <option value="≤" <c:if test="${baseLine.standard=='≤'}"> selected="selected"> </c:if>> ≤ </option>
					  </select>
				  </div>
				  <div class="layui-input-inline"  id="standardValueDiv" style="width: 120px">
					  <input type="number" name="standardValue" value="${baseLine.standardValue}" maxlength="50" lay-verify="required" placeholder="值" autocomplete="off" class="layui-input">
				  </div>
				  <div class="layui-input-inline" style="width: 50px;">
						<div id="addCommBtn1" onclick="addRow(this)"><i class="layui-icon">&#xe654;</i></div>
				  </div>
		  	</div>
	  	</div>
<!-- 	  <div class="layui-form-item" id="lineListHtml"> -->
<!-- 		  <div class="layui-inline"> -->
<!-- 			  <label class="layui-form-label">地区</label> -->
<!-- 			  <div class="layui-input-inline" style="width: 360px;"> -->
<%-- 				  <infopub:combox id="add_sgCityId" layFilter="add_sgCityId"   entireName="-地区" name="sgCityIds" value="${baseLine.sgCityIds}" valueField="id" textField="cityName" serviceBeanId="citySurveyServiceImpl" whereMap="&orderCondition=to_number(ref_province_id),to_number(ref_city_id),to_number(ref_area_id)" laySearch="true"></infopub:combox> --%>
<!-- 			  </div> -->
<!-- 		  </div> -->
<!-- 	  </div> -->
	  <div class="layui-form-item" id="lineListHtml">
		  <div class="layui-inline">
			  <label class="layui-form-label">备注说明</label>
			  <div class="layui-input-inline" style="width: 360px;">
				  <textarea style="width: 360px;height: 60px" name="remark">${baseLine.remark}</textarea>
			  </div>
		  </div>
	  </div>
	  <div class="layui-form-item layui-hide">
		  <input type="button" lay-submit lay-filter="add_line_form_submit" id="add_line_form_submit" value="确认">
	  </div>
  </form>

<script>
	var editAddCityId = null;
	var editAddAreaId = null;
  	layui.config({
    	base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
  	}).extend({
    	index: 'lib/index' //主入口模块
    	//,bioarea: 'bioarea'
  	}).use(['index', 'table', 'set', 'transfer', 'laydate', 'laypage', 'layer'], function(){
    	var $ = layui.$
    	,form = layui.form
    	,table = layui.table
    	,element = layui.element
    	,laypage = layui.laypage
    	//, bioarea = layui.bioarea //省市区县三级联动
    	,laydate = layui.laydate
    	,layer = layui.layer;

    	//tab重新渲染宽度
    	element.on('tab(component-tabs-brief)', function(obj){
    		$(window).resize();
    	});

    	var dataSS = []; //列表集合
    	var statusCols = []; //表头集合
		var perPage = 10;
		var nowPage = 1;
		var firstReqData = {page:nowPage, limit:perPage};
    	tableInital(nowPage, perPage, firstReqData, true); //初始化加载
    	// ajax插询需要添加的标准列
    	function tableInital(pageNum, pageSize, reqData, first){
    		var $ = layui.$;
       		$.ajax({
       			type : 'post',
       			url : basePath + '/baseLine/queryDataByCondition?hrStaffApplyId=${SESSION_KEY_USER_DETAIL.hrStaffId }',  //请求数据接口
       			async : false,
       			data: reqData,
       			success:function(result){
       				if(!result.success) {
       					layer.msg(result.msg,{icon: 7});
       					return;
       				}
       				if(result.data.length < 1){
       					dataSS = [];
       					statusCols = [];
       				} else {
       					//初始化加载表格渲染和分页查询
           				tableTitleAndShow(result.data);
           				console.info(dataSS,statusCols);
       				}
					table.render({
//       	     	  		url : basePath + '/baseLine/queryDataByCondition?hrStaffApplyId=${SESSION_KEY_USER_DETAIL.hrStaffId }',  //请求数据接口
       	                elem: '#LAY-strandard-create-manage',
       	        		cols: [statusCols],
       	        		data : dataSS,
       	                done: function(res, curr, count){
       	                }
       	            });
					if(first) tablePage(pageNum,result.count);

					table.reload('LAY-strandard-create-manage'); //数据刷新
       			}
    	   	});
    	}

    	 //分页请求重写
    	function tablePage(curr,count) {
    		console.info(curr,count,laypage);
    		laypage.render({
                elem: 'table-foot',
                count,
                curr,
                limit: perPage,
                jump: function(obj,first){
					nowPage = obj.curr;
                    if(!first){
                    	var reqData = {page:nowPage, limit:perPage};
                    	tableInital(nowPage , perPage, reqData)
                    }
                }
            });
    	 }
    	// 通过后台参数生成自动列表并渲染
    	function tableTitleAndShow(data){
    		var dataFiled = []; //表头集合
			dataSS=[];
			statusCols = [];
    		for (var i = 0; i < data.length; i++) {
    			dataSS[i] = $.extend({}, data[i] , data[i].standardSubJson);
    			for(var key in data[i].standardSubJson){
    				if(dataFiled.indexOf(key) < 0){
    					dataFiled.push(key);
    				}
    			}
    		}
			var colsNum = 2;
			if (dataFiled.length > 0) {
				for (var i = 0; i < dataFiled.length; i++) {
					colsNum += 1;
					if(dataFiled[i]=='入库情况'){
						statusCols[colsNum] = {field: dataFiled[i], title: dataFiled[i], align:'center', width: 150,templet: function(d){

							if(d.入库情况&&d.入库情况==0){//0启用1禁用
								return "未入库";
							}else if(d.入库情况&&d.入库情况==1){
								return "已入库";
							}else {
								return  ''
							}
						}}
					}else {
						statusCols[colsNum] = {field: dataFiled[i], title: dataFiled[i], align:'center', width: 150,
						}
					}
				}
			} else {
				colsNum -= 1;
			}
			statusCols[0]= {type: 'checkbox', fixed: 'left', width : 50};
			statusCols[1]= {field: 'sgCityName', title: '城市', width: 170, fixed: 'left'};
			statusCols[colsNum + 2] = {field: 'flag', title: '状态',  width: 200, templet: function(d){
					if(d.flag == 1){//0启用1禁用
						return "禁用";
					}else{
						return "启用";
					}
				}
			}
			statusCols[colsNum + 3]= {field: 'remark', title: '备注', width: 160};
			statusCols[colsNum + 4]= {title: '操作', width: 300, align:'center', fixed: 'right', templet: function(d){
					var optStr ="";
					optStr += '<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-form"></i>修改</a>';
					if(d.flag == 1){//0启用1禁用
						optStr += '<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="use"><i class="layui-icon layui-icon-ok"></i>启用</a>';
					}else{//状态为启用
						optStr += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="pause"><i class="layui-icon layui-icon-pause"></i>禁用</a>';
					}
					optStr += '<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="copy"><i class="layui-icon layui-icon-release"></i>复制</a>';
					optStr += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</a>';
					return optStr;
				}
			};
    	}
		//监听搜索
		form.on('submit(LAY-preProject-search)', function(data){
			var reqData = trimData(data);
			reqData.page = nowPage;
			reqData.limit = perPage;
			tableInital(nowPage, perPage, reqData, true);
			//table.reload('LAY-strandard-create-manage');
			/**table.reload('LAY-strandard-create-manage', {page: {curr: 1},
				where: trimData(data)
			});**/
		});
		//重置清空
		form.on('submit(LAY-user-back-reset)', function(data){
			reset_form('query-form');
			//额外处理select
			$("#query-form-state").val('');
			$('#query_city').html('');
	    	$('#query_area').html('');
			form.render();
		});
		// 监听select事件
		form.on("select(standardName)", function(data){
			//console.log(data.othis.parent().html());
            if(data.value == "4"){ //入库情况
            	//data.othis.parent().next().next().children().css("background-color", 'red');
            	data.othis.parent().next().hide();
            	data.othis.parent().next().next().children().remove();
				var selectValueHtml = "";
				selectValueHtml += '<select name="standardValue" lay-verify="required" >';
				selectValueHtml += '<option value="1" <c:if test="${baseLine.standardValue=='已入库'}">selected="selected"></c:if>>已入库</option>';
				selectValueHtml += '<option value="0" <c:if test="${baseLine.standardValue=='未入库'}">selected="selected"></c:if>>未入库</option>';
				selectValueHtml += '</select>';
				data.othis.parent().next().next().append(selectValueHtml);
            }else{
            	var inputValueHtml = "";
            	inputValueHtml += '<input type="number" name="standardValue" value="${baseLine.standardValue}" maxlength="50" lay-verify="required" placeholder="值" autocomplete="off" class="layui-input">';
            	data.othis.parent().next().show();
            	data.othis.parent().next().next().children().remove();
            	data.othis.parent().next().next().append(inputValueHtml);
            	//data.othis.parent().next().next().children().css("background-color", 'blue');
            }
			//重新渲染select数据
			form.render();
	    });

		// 查询-省份获取市
	    form.on('select(query_provinceId)', function(data){
	    	console.log("省份点击事件");
	    	var proId = data.value;
	    	$('#query_city').html('');
	    	$('#query_area').html('');
			$.ajax({
				type : "POST", //提交方式
				url : basePath + '/citySurvey/getCityByPro',//路径
				data : {
					"proId" :proId
				},//数据，这里使用的是Json格式进行传输
				success : function(result) {//返回数据根据结果进行相应的处理
					if(result.flag==true){
						var strBuffer = "";
						strBuffer+= '<option value="">请选择市</option>';
						layui.$.each(result.citys, function(i,item){
							if(item.id != null && item.sname != null){
								strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
							}
				        });
						$('#query_city').append(strBuffer);
						form.render();
					}else{
						layer.msg('数据通信异常~',{icon: 0});
					}
				}
			});
		});

		// 查询-市获取县
	    form.on('select(query_cityId)', function(data){
	    	console.log("城市点击事件");
	    	var cityId = data.value;
	    	$('#query_area').html('');
			$.ajax({
				type : "POST", //提交方式
				url : basePath + '/citySurvey/getAreaByCity',//路径
				data : {
					"cityId" :cityId
				},//数据，这里使用的是Json格式进行传输
				success : function(result) {//返回数据根据结果进行相应的处理
					if(result.flag==true){
						var strBuffer = "";
						strBuffer+= '<option value="">请选择区/县</option>';
						layui.$.each(result.areas, function(i,item){
							if(item.id != null && item.sname != null){
								strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
							}
				        });
						$('#query_area').append(strBuffer);
						form.render();
					}else{
						layer.msg('数据通信异常~',{icon: 0});
					}
				}
			});
		});

		// 新增-省份获取市
	    form.on('select(select_provinceId)', function(data){
	    	console.log("省份点击事件");
	    	var proId = data.value;
	    	$('#select_city').html('');
	    	$('#select_area').html('');
			$.ajax({
				type : "POST", //提交方式
				url : basePath + '/citySurvey/getCityByPro',//路径
				data : {
					"proId" :proId
				},//数据，这里使用的是Json格式进行传输
				success : function(result) {//返回数据根据结果进行相应的处理
					if(result.flag==true){
						var strBuffer = "";
						strBuffer+= '<option value="">请选择</option>';
						layui.$.each(result.citys, function(i,item){
							if(item.id != null && item.sname != null){
								strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
							}
				        });
						$('#select_city').append(strBuffer);
						form.render();
						if (editAddCityId != null) {
							//编辑等数据渲染后在进行选择
							$('select[name=refCityId]').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + editAddCityId + ']').click();
							$('select[name=refCityId]').find("option[value=" + editAddCityId + "]").prop("selected", true);
							$('select[name=refCityId]').val(editAddCityId);
							//编辑后重置，避免新增出现问题
							editAddCityId = null;
						}
					}else{
						layer.msg('数据通信异常~',{icon: 0});
					}
				}
			});
		});

		// 新增-市获取县
	    form.on('select(select_city)', function(data){
	    	console.log("城市点击事件");
	    	var cityId = data.value;
	    	$('#select_area').html('');
			$.ajax({
				type : "POST", //提交方式
				url : basePath + '/citySurvey/getAreaByCity',//路径
				data : {
					"cityId" :cityId
				},//数据，这里使用的是Json格式进行传输
				success : function(result) {//返回数据根据结果进行相应的处理
					if(result.flag==true){
						var strBuffer = "";
						strBuffer+= '<option value="">请选择</option>';
						layui.$.each(result.areas, function(i,item){
							if(item.id != null && item.sname != null){
								strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
							}
				        });
						$('#select_area').append(strBuffer);
						form.render();
						if (editAddAreaId != null) {
							$('select[name=refAreaId]').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + editAddAreaId + ']').click();
							$('select[name=refAreaId]').find("option[value=" + editAddAreaId + "]").prop("selected", true);
							$('select[name=refAreaId]').val(editAddAreaId);
							editAddAreaId = null;
						}
					}else{
						layer.msg('数据通信异常~',{icon: 0});
					}
				}
			});
		});

	    // 弹出层通用方法
      function openTableLayui(baselineId, method){
    	  	console.log("打开弹出层" + baselineId);
        	var $ = layui.$;
        	var methodTitle;
    		if(method == "edit"){
    			methodTitle = "修改";
    		}else if(method == "view"){
    			methodTitle = "查看";
    		}else if(method == "copy"){
    			methodTitle = "复制";
    		}else if(method == "add"){
    			$('#select_city').html('');
    	    	$('#select_area').html('');
    			methodTitle = "新增";
    		}
        	var maxInd = $("div[id^='linkRow']").length;
    		$("div[id^='linkRow']").each(function(){
    		    if($(this).attr("id") != "linkRow1"){
    			   $(this).remove();
    		    }
    		});
        	layer.open({
    			  type: 1
    			  ,title: methodTitle + '底线标准'
    			  ,content: $('#add_line_form')
    			  ,area: layui.admin.screen() < 2 ? ['80%', '450px'] : ['600px','450px']
    			  ,btn: ['确定', '取消']
    			  ,btnAlign: 'c'
    			  ,yes: function(index, layero){
    				  	var submitID = 'add_line_form_submit'
    						,submit = layero.contents().find('#'+ submitID);
    				  	// form表单提交
    			  		form.on('submit('+ submitID +')', function(data){
    			  			// 获取省市区县名称存在名称中
    			  			 if(method == "add"){
    			  				method = "save";
    			     		 }
    			  			if(method == "copy"){
    			  				method = "save";
    			     		 }
    			  			if(checkSgCityName(baselineId, method)){
    			  				submitFormAjax(method, index,function () {
    			  					var reqData = {page:nowPage, limit:perPage};
									tableInital(nowPage,perPage, reqData);
								});
    			  			}
    			  		});
    			  		submit.trigger('click');
    			  }
    		});
        }

    	// 监听操作列
    	table.on('tool(LAY-strandard-create-manage)', function(obj){
      		var data = obj.data;
 			if(obj.event === 'delete'){
      			layer.confirm('确定要删除？',{icon:3, title :'提示'}, function(index){
      				submitAjaxDelete(data.id, index);
      				table.reload('LAY-strandard-create-manage'); //数据刷新
       			})
       		}else if(obj.event === 'use'){
       			layer.confirm('确定要启用该地区的标准？',{icon:3, title :'提示'}, function(index){
       				updateBaselineFlag(data.id, index, 0);
       			})
       		}else if(obj.event === 'pause'){
       			layer.confirm('确定要禁用该地区的标准信息？',{icon:3, title :'提示'}, function(index){
       				updateBaselineFlag(data.id, index, 1);
       			})
       		}else if(obj.event === 'view'){ //查看详情
       			openTableLayui(data.id, 'view');
       			cleanForm(); //　清空页面缓存信息
        		form.val('add_line_form', data);
    			editRow(data); //渲染循环显示标准信息

       		}else if(obj.event === 'copy'){ //复制
       			openTableLayui(null, 'copy');
       			cleanForm(); //　清空页面缓存信息
        		form.val('add_line_form', data);
    			editRow(data); //渲染循环显示标准信息

       		}else if(obj.event === 'edit'){ //修改
       			openTableLayui(data.id, 'edit');
       			cleanForm(); //　清空页面缓存信息
        		form.val('add_line_form', data);
    			editRow(data); //渲染循环显示标准信息
       		}
 			form.render(); //渲染
      });

      // 按钮事件
      var active = {
		  reload: function (data) {
	           var index = layer.msg('查询中，请稍后...', { icon: 16, time: false, shade: 0 });
	           setTimeout(function () {
	               table.reload('LAY-strandard-create-manage',{page:{curr:1 },
	            	   where: trimData(data)
	               })
	               layer.close(index);
	           },800)
	       },
	       add: function(){
	    	  //parent.layui.index.openTabsPage(basePath + '/baseLine/add','新增底线标准 > 新建');
	    	  openTableLayui(null, 'add');
	    	  cleanForm();
	       }
    }
    // data-type事件
    $('.layui-btn.layuiadmin-btn-admin').on('click', function(){
	      var type = $(this).data('type');
	      active[type] ? active[type].call(this) : '';
	});

    function cleanForm(){
   		var $ = layui.$;
   		 $('select[name=refProvinceId]').val('');
   	     $('select[name=refCityId]').val('');
   	     $('select[name=refAreaId]').val('');
   	     $('select[name=standardName]').val('');
   	     $('select[name=standardRule]').val('');
   	     $('select[name=standardValue]').val('');
   	     $('input[name=standardValue]').val('');
   	     $('textarea[name=remark]').val('');
   	     form.render('select');
   	     clean_form("add_line_form");//清空表单
   	}
});

function checkSgCityName(checkId, method){
  	var $ = layui.$;
  	var refProvinceName = $("select[name=refProvinceId]").find("option:selected").text().trim();
	var refCityName = $("select[name=refCityId]").find("option:selected").text().trim();
	var refAreaName = $("select[name=refAreaId]").find("option:selected").text().trim();
	if(refProvinceName=="请选择"){
		refProvinceName = "全国";
	}
	if(refCityName=="请选择"){
		refCityName="";
	}
	if(refAreaName=="请选择"){
		refAreaName="";
	}
	var sgCityName = refProvinceName + refCityName + refAreaName;
	// 验证地区是否重复
	if(method == "edit" && (checkId == null || checkId == "" || checkId == "undefined")){
		layer.confirm(checkId + ",验证地区标准ID获取失败！",{icon:0, title :"提示"});
		return false;
	}
	if(!checkField(checkId, sgCityName, method)){
		layer.alert(sgCityName + ",,地区标准已存在！" ,{icon:0, title :"提示"});
		return false;
	}
	$("input[name=sgCityName]").val(sgCityName);
	//console.log(refProvinceName + "==++++" + refCityName + "-----" + refAreaName);
	return true;
}
//提交 Ajax 成功后，静态更新表格中的数据
function submitFormAjax(method, openTableId,cb){
	var $ = layui.$;
	$.ajax({
		type : 'post',
		url : basePath + '/baseLine/' + method,
		data: $("#add_line_form").serialize(),
		success:function(result){
			if(result.success){
				clean_form("add_line_form");//清空表单
				layer.close(openTableId); //关闭弹层
				if(cb) cb();
			}else{
				layer.msg(result.msg,{icon: 7});
			}
		}
	 });
}
// 删除通用方法
function submitAjaxDelete(deleteId, closeIndex){
	var $ = layui.$;
	$.ajax({
		type : 'post',
		url : basePath + '/baseLine/delete',
		data : {
			"id" :  deleteId
		},
		success:function(result){
			if(result){
				layer.close(closeIndex); //关闭弹层
			}else{
				layer.msg(result.msg, {icon: 0});
			}
		}
	});
}

function updateBaselineFlag(updateId, index, flag){
	var $ = layui.$;
	$.ajax({
		type : 'post',
		url : basePath + '/baseLine/updateByFlagKey',
		data : {
			"id" : updateId,
			"flag" : flag
		},//数据，这里使用的是Json格式进行传输
		success:function(result){
			if(result){
				layer.close(index); //关闭弹层
			}else{
				layer.msg('数据通信异常~',{icon: 0});
			}
		}
	});
}
// 验证地区是否存在
function checkField(checkId, sgCityName, method){
	var checkFlag = false;
	var $ = layui.$;
	$.ajax({
		type : 'post',
		url : basePath + '/baseLine/checkSgName',
		async : false,
		data : {
			"id" : checkId,
			"method" : method,
			"sgCityName" : sgCityName

		},//数据，这里使用的是Json格式进行传输
		success:function(result){
			checkFlag = result;
		}
	});
	return checkFlag;
}
//新增一行
function addRow(t){
		var $ = layui.$;
	var thisid = $(t).attr("id").substring(10);
		thisid = $("div[id=linkRow" + thisid + "]").find("div:first").find("label").html();
	thisid = parseInt(thisid);
	var nextIndex = parseInt(thisid) + 1;
	var maxInd = $("div[id^='linkRow']").length;
	$("div[id^='linkRow']").each(function(){
		var tId = $(this).attr("id").substring(7);
		tId = parseInt(tId);
	  	if(tId > maxInd){
	  		maxInd = parseInt(tId);
	  	}
	  	var thisIndex = $(this).find("div:first").find("label").html();
	  	thisIndex = parseInt(thisIndex);
	  	var nextId = thisIndex + 1;
	  	if(thisIndex > thisid) {
	  		$("div[id=linkRow" + tId + "]").find("div:first").find("label").html(nextId);
	  	}
	});
	var ind = maxInd + 1;
		var standardDiv = $("#standardSelect").clone();
	var strandardRuleDiv = $("#strandardRuleSelect").clone();
	var lineOneHtml = '';
	lineOneHtml +='<div class="layui-form-item" id ="linkRow'+ind+'">';
	lineOneHtml +='<div class="layui-inline">';
	lineOneHtml +='	  <label class="layui-form-label">标准'+ind+'</label>';
	lineOneHtml +='	  <div class="layui-input-inline" style="width: 150px;">';
	lineOneHtml += standardDiv.html();
	lineOneHtml +='	  </div>';
	lineOneHtml +='	  <div class="layui-input-inline" style="width: 70px">';
	lineOneHtml += strandardRuleDiv.html();
	lineOneHtml +='	  </div>';
	lineOneHtml +='	  <div class="layui-input-inline" style="width: 120px">';
	lineOneHtml +='		  <input type="number" name="standardValue" value="${baseLine.standardValue}" maxlength="50" lay-verify="required" placeholder="值" autocomplete="off" class="layui-input">';
	lineOneHtml +='	  </div>';
	lineOneHtml +='	  <div class="layui-input-inline" style="width: 50px;">';
	lineOneHtml +='			<div id="delLineRow'+ind+'" onclick="deleteLineRow('+ind+');"><i class="layui-icon">&#xe640;</i></div>';
	lineOneHtml +='	  </div>';
	lineOneHtml +='</div>';
  	lineOneHtml +='</div>';
  	$('#lineListHtml').before(lineOneHtml);
	layui.form.render();
};
//修改批量插入
function editRow(data){
	var $ = layui.$;
	$("div[id^='linkRow']").each(function(){
		if(!($(this).attr("id")== "linkRow1")){
			$(this).remove();
		}
	});
	 //模拟选中

	 $('select[name=refProvinceId]').find("option[value=" + data.refProvinceId + "]").prop("selected", true);
	 $('select[name=refProvinceId]').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + data.refProvinceId + ']').click();
	 $('select[name=refProvinceId]').val(data.refProvinceId);
	 editAddCityId = data.refCityId;
	 //$('select[name=refCityId]').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + data.refCityId + ']').click();
	 //$('select[name=refCityId]').find("option[value=" + data.refCityId + "]").prop("selected", true);
	 //$('select[name=refCityId]').val(data.refCityId);
	 //getAddCityByPro(data.refProvinceId, data.refCityId);
	 editAddAreaId = data.refAreaId;
	 //$('select[name=refAreaId]').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + data.refAreaId + ']').click();
	 //$('select[name=refAreaId]').find("option[value=" + data.refAreaId + "]").prop("selected", true);
	 //$('select[name=refAreaId]').val(data.refAreaId);
// 	 $('select[name=refAreaId]').next().children("dl").find('.layui-this').click();
	 //getAddAreaByCity(data.refCityId, data.refAreaId);
	 layui.form.render('select');

// 	 $('#select_provinceId').siblings("div.layui-form-select").children('dl').children("dd")..click();
// 	 $('#select_city').siblings("div.layui-form-select").find('dl').find("selected").click();
// 	 $('#select_area').siblings("div.layui-form-select").find('dl').find("selected").click();

	var standardRow = data.standardSubs;
	if(standardRow.length > 0){
		for (var i = 1; i < standardRow.length; i++) {
			editHtml(i+1, standardRow[i]);
		}
		//console.log(lineRow.find("select[name=standardRule]").html());
		// 第一列的数据插入
		var lineRow = $("#linkRow1").children();
		if(standardRow[0].standardCode != '4'){
			lineRow.find("select[name=standardRule]").val(standardRow[0].standardRule);
			lineRow.find("select[name=standardRule]").parent().show();
			lineRow.find("#standardValueDiv").children().remove();
			var inputValueHtml = "";
		    inputValueHtml += '<input type="number" name="standardValue" maxlength="50" lay-verify="required" placeholder="值" autocomplete="off" class="layui-input">';
			lineRow.find("#standardValueDiv").append(inputValueHtml);
			lineRow.find("#standardValueDiv").children().val(standardRow[0].standardValue);
		}else{
			//选中入库情况
			var lineOneHtmlInit = '';
			lineOneHtmlInit += '<select name="standardValue" lay-verify="required" >';
			lineOneHtmlInit += '<option value="1">已入库</option>';
			lineOneHtmlInit += '<option value="0">未入库</option>';
			lineOneHtmlInit += '</select>';

			//console.log(lineRow.find("select[name=standardRule]"));

			lineRow.find("select[name=standardRule]").parent().hide();;
			lineRow.find("#standardValueDiv").children().remove();
			lineRow.find("#standardValueDiv").append(lineOneHtmlInit);
			lineRow.find("#standardValueDiv").children().val(standardRow[0].standardValue);
		}
		lineRow.find("select[name=standardName]").val(standardRow[0].standardCode);
	}
	layui.form.render();
}

//修改循环显示标准明细
function editHtml(editNum, obj, type){
	var $ = layui.$;
	var standardDiv = $("#standardSelect").clone();
	var strandardRuleDiv = $("#strandardRuleSelect").clone();
	var lineOneHtml = '';
	lineOneHtml +='<div class="layui-form-item" id ="linkRow'+editNum+'">';
	lineOneHtml +='<div class="layui-inline">';
	lineOneHtml +='	  <label class="layui-form-label">标准'+editNum+'</label>';
	lineOneHtml +='	  <div class="layui-input-inline" style="width: 150px;">';
	lineOneHtml += standardDiv.html();
	lineOneHtml +='	  </div>';
	if(obj.standardCode != '4'){
		lineOneHtml +='	  <div class="layui-input-inline" style="width: 70px">';
		lineOneHtml += strandardRuleDiv.html();
		lineOneHtml +='	  </div>';
		lineOneHtml +='	  <div class="layui-input-inline" style="width: 120px">';
		lineOneHtml +='		  <input type="number" name="standardValue" value="'+ obj.standardValue +'" maxlength="50" lay-verify="required" placeholder="值" autocomplete="off" class="layui-input">';
		lineOneHtml +='	  </div>';
	}else{
		lineOneHtml += '<div class="layui-input-inline" style="width: 120px">';
		lineOneHtml += '	<select name="standardValue" lay-verify="required" >';
		lineOneHtml += '		<option value="1">已入库</option>';
		lineOneHtml += '		<option value="0">未入库</option>';
		lineOneHtml += '	</select>';
		lineOneHtml += '</div>';
	}
	lineOneHtml +='	  <div class="layui-input-inline" style="width: 50px;">';
	lineOneHtml +='			<div id="delLineRow'+ editNum +'" onclick="deleteLineRow('+editNum+');"><i class="layui-icon">&#xe640;</i></div>';
	lineOneHtml +='	  </div>';
	lineOneHtml +='</div>';
 	lineOneHtml +='</div>';
 	$('#lineListHtml').before(lineOneHtml);
 	//选中select修改详情赋值
 	var lineRowTwo = $("#linkRow" + editNum).children();
	if(obj.standardCode != '4'){
		lineRowTwo.find("select[name=standardRule]").val(obj.standardRule);
		lineRowTwo.find("select[name=standardRule]").parent().show();
 	}else{
 		lineRowTwo.find("select[name=standardRule]").parent().hide();
		lineRowTwo.find("#standardValueDiv").children().remove();
		lineRowTwo.find("#standardValueDiv").children().val(obj.standardValue);
 	}
	lineRowTwo.find("select[name=standardName]").val(obj.standardCode);
}

//刪除标准
function deleteLineRow(id){
 	var $ = layui.$;
 	layui.layer.confirm('确定删除？',{icon:3, title :'提示'}, function(index){
	    var rowLength = $("div[id^='linkRow']").length;
	    $("div[id=linkRow" + id + "]").remove();
		layui.layer.close(index);
	});
}
 //'请输入正确数字，且保留两位小数！'
function isNumberAndFloat1(str) {
	var $ = layui.$, form = layui.form
	if (str.value == '' || str.value == null) {
		return;
	}
	var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;

	var boolrgx = rgx.test(str.value);// true
	if (boolrgx) {
		return true;
	} else {
		str.value =0;
		layer.msg('请输入正确数字，且保留两位小数！');
		return false;
	}
}
  </script>
</body>
</html>

